package uicgas.register;

import javax.activation.UnsupportedDataTypeException;

import uicgas.communication.impl.AbstractCommunicationImpl;
import uicgas.globaldata.ClientTypes;
import uicgas.globaldata.ControlMessage;
import uicgas.globaldata.Messages;
import uicgas.register.remotecmds.ActivatePump;
import uicgas.register.remotecmds.AnnouncePump;
import uicgas.register.remotecmds.AnnounceSelf;
import uicgas.register.remotecmds.AnnounceTransaction;
import uicgas.register.remotecmds.ChangePumpState;
import uicgas.register.remotecmds.NotifyAssistance;
import uicgas.register.remotecmds.NotifyCardInvalid;
import uicgas.register.remotecmds.PumpState;
import uicgas.tools.UicGasGeneralException;

public class Comunications extends AbstractCommunicationImpl
{
	private RegisterLogic register;
	//private Socket connection = null;
	//private static final Logger LOGGER = LogHelper
	//.getLogger(AbstractCommunicationImpl.class);
	
	public Comunications(RegisterLogic register)
	{
		super(ClientTypes.REGISTER);
		this.register = register;
	}
	/**
	* When ControlMessage came in from Server, process it here.
	* @param messageIn
	*/
	protected void processControlMessageFromServer(ControlMessage messageIn)
	{
		Messages message = messageIn.getMessage();
		
		if(message == Messages.ANNOUNCESELF)
		{
			new AnnounceSelf(register, this).executeRemoteCommand(messageIn.getPayload());
		}
		else if(message == Messages.CHANGEPUMPSTATE)
		{
			new ChangePumpState(register, this).executeRemoteCommand(messageIn.getPayload());
		}
		else if(message == Messages.NOTIFYREGISTERASSISTANCENEEDED)
		{
			new NotifyAssistance(register, this).executeRemoteCommand(messageIn.getPayload());
		}
		else if(message == Messages.NOTIFYASSISTANCE)
		{
			new NotifyAssistance(register, this).executeRemoteCommand(messageIn.getPayload());
		}
		else if (message == Messages.INVALID)
		{
			//new NotifyCardInvalid(register, this).executeRemoteCommand(messageIn.getPayload());
		}
		else if (message == Messages.VALID)
		{
			new ActivatePump(register, this).executeRemoteCommand(messageIn.getPayload());
		}
		else if (message == Messages.ANNOUNCEALLCONNECTEDPUMPS)
		{
			new AnnouncePump(register, this).executeRemoteCommand(messageIn.getPayload());
		}
		else if (message == Messages.CHANGEPUMPSTATE)
		{
			new PumpState(register, this).executeRemoteCommand();
		}
		else if (message == Messages.ANNOUNCETRANSACTION)
		{
			new AnnounceTransaction(register, this).executeRemoteCommand();
		}
		else
		{
			throw new UicGasGeneralException(new UnsupportedDataTypeException(
					message.toString()));
		}
	}

	/**
	* Generate and return a unique ID representing the component;<br>
	* If the ID is not unique in Server side,
	* this method may be invoke again, until unique ID got.
	*
	* @return unique ID representing the component
	*/
	protected int generateUniqueComponentID()
	{
		register.generateNewID();
		return register.getID();
	}
	
//	public void start()
//	{
//		new Thread()
//		{
//			@Override
//			public void run()
//			{
//				startInternal();
//			}
//		}.start();
//	}
//	
//	private void startInternal()
//	{
//		establishConnectionWithStation();
//
//		int id;
//
//		do
//		{
//			id = generateUniqueComponentID();
//			if (LOGGER.isDebugEnabled())
//			{
//				LOGGER.debug("Ready to register self to Station using ID[" + id
//						+ "]. ");
//			}
//
//			registerSelfToStation(id);
//		}
//		while (!isSucessfullyRegistered(id));
//
//		startToListenMessagesFromStation();
//	}
//
//	private boolean isSucessfullyRegistered(int id)
//	{
//		ObjectInputStream inputStream;
//		try
//		{
//			inputStream = new ObjectInputStream(connection.getInputStream());
//			ControlMessage messageIn = (ControlMessage) inputStream
//					.readObject();
//
//			Messages message = messageIn.getMessage();
//			if (Messages.IDOK == message)
//			{
//				if (LOGGER.isDebugEnabled())
//				{
//					LOGGER.debug("Successfully register self to Station using ID["
//							+ id + "]. ");
//				}
//
//				return true;
//			}
//		}
//		catch (IOException ioe)
//		{
//			throw new UicGasGeneralException(ioe);
//		}
//		catch (ClassNotFoundException e)
//		{
//			throw new UicGasGeneralException(e);
//		}
//
//		if (LOGGER.isDebugEnabled())
//		{
//			LOGGER.debug("Failed register self to Station using ID[" + id
//					+ "]. Trying next ID. ");
//		}
//
//		return false;
//	}
//
//	private void establishConnectionWithStation()
//	{
//		if (LOGGER.isDebugEnabled())
//		{
//			LOGGER.debug("Begin to create Socket to Station. ");
//		}
//		try
//		{
//			connection = new Socket(RConfig.SERVER_IP, RConfig.SERVER_PORT);
//		}
//		catch (IOException e)
//		{
//			throw new UicGasGeneralException("Can not connect to Station["
//					+ RConfig.SERVER_IP + ":" + RConfig.SERVER_PORT + "] ", e);
//		}
//		if (LOGGER.isDebugEnabled())
//		{
//			LOGGER.debug("End to create Socket to Station. " + connection);
//		}
//	}
//
//	private void registerSelfToStation(int id)
//	{
//		SelfAnnouncement selfAnnouncement = new SelfAnnouncement(id, -1);
//		ControlMessage controlMessage = new ControlMessage(
//				Messages.CONNECTREGISTER, selfAnnouncement);
//		sendData(controlMessage);
//	}
//
//	private void startToListenMessagesFromStation()
//	{
//		try
//		{
//			ControlMessage messageIn = null;
//			ObjectInputStream inputStream = null;
//			while (true)
//			{
//				inputStream = new ObjectInputStream(connection.getInputStream());
//				messageIn = (ControlMessage) inputStream.readObject();
//				if (LOGGER.isDebugEnabled())
//				{
//					LOGGER.debug("Get ControlMessage from Server - ["
//							+ ControlMessage.class.getSimpleName() + "] ");
//				}
//
//				processControlMessageFromServer(messageIn);
//			}
//		}
//		catch (IOException ioe)
//		{
//			throw new UicGasGeneralException(ioe);
//		}
//		catch (ClassNotFoundException e)
//		{
//			throw new UicGasGeneralException(e);
//		}
//	}
//
//	@Override
//	public void sendData(ControlMessage messageOut)
//	{
//		if (connection == null)
//		{
//			LOGGER.error("Socket has not been established. ");
//
//			return;
//		}
//
//		if (LOGGER.isDebugEnabled())
//		{
//			LOGGER.debug("Begin to send ControlMessage["
//					+ ToStringBuilder.reflectionToString(messageOut) + "]. ");
//		}
//
//		try
//		{
//			ObjectOutputStream outputStream = new ObjectOutputStream(
//					connection.getOutputStream());
//			outputStream.writeObject(messageOut);
//		}
//		catch (IOException e)
//		{
//			throw new UicGasGeneralException(e);
//		}
//
//		if (LOGGER.isDebugEnabled())
//		{
//			LOGGER.debug("End to send ControlMessage["
//					+ ToStringBuilder.reflectionToString(messageOut) + "]. ");
//		}
//
//	}
}
